﻿using AutoMapper;
using B.S.BasicData.API.Write.Application.Command.User;
using B.S.BasicData.Domain.Entities.UserRoleMenu;
using B.S.BasicData.ErrorCode;
using B.S.BasicData.Infrastructure.Interface;
using MediatR;

namespace B.S.BasicData.API.Write.Application.Handler.User
{
    /// <summary>
    /// 修改用户信息请求命令处理类
    /// </summary>
    public class UpdateUserHandler:IRequestHandler<UpdateUserCommand,ApiResult<int>>
    {
        IBaseRepository<UserModel> userRep;
        IMapper mapper;

        public UpdateUserHandler(IBaseRepository<UserModel> userRep,IMapper mapper)
        {
            this.userRep = userRep;
            this.mapper = mapper;
        }

        public Task<ApiResult<int>> Handle(UpdateUserCommand request, CancellationToken cancellationToken)
        {
            try
            {
                ApiResult<int> res = new ApiResult<int>();

                var user = userRep.GetAll().Where(x => x.Id == request.id).FirstOrDefault();
                if (user == null)
                {
                    res.Msg = "用户信息不存在";
                    res.Code=ApiEnum.Fail;
                    return Task.FromResult(res);
                }

                var username = userRep.GetAll().Where(x => x.UserName == request.userName&&!x.IsDeleted&&x.Id!=request.id).FirstOrDefault();
                if (username != null)
                {
                    res.Msg = "用户名已存在";
                    res.Code = ApiEnum.Fail;
                    return Task.FromResult(res);
                }

                var entity = mapper.Map(request, user);
                entity.UpdateDate = DateTime.Now;
                entity.UpdateName=user.UserName;

                int r = userRep.UpdateAsync(entity).Result;

                if (r > 0)
                {
                    res.Msg = "修改用户信息成功";
                    res.Data = r;
                    res.Code = ApiEnum.Success;
                }
                else
                {
                    res.Msg = "修改用户信息失败";
                    res.Code = ApiEnum.Fail;
                }

                return Task.FromResult(res);
            }
            catch (Exception)
            {

                throw;
            }
        }
    }
}
